/*
 * Copyright (c) 2011 Jean-Marc Perronne
 * Ensisa, 12 rue des Freres Lumieres, F-68093 Mulhouse cedex
 * All rights reserved.
 *
 * The copyright of this software is owned by Werner Randelshofer. 
 * You may not use, copy or modify this software, except in  
 * accordance with the license agreement you entered into with  
 * Jean-Marc Perronne. For details see accompanying license terms. 
 */

package fr.uha.ensisa.jmp.drone.ui.instrument;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import fr.uha.ensisa.jmp.drone.ui.instrument.dial.Dial;
import fr.uha.ensisa.jmp.drone.ui.instrument.dial.renderer.DefaultDialRenderer;


public class CompassRenderer extends DefaultDialRenderer
{
	private BufferedImage dialImage;
	private BufferedImage needleImage;
	private AffineTransform needleTransform;
	
	private final Dimension sizeCache;

	public CompassRenderer(Dial dial, String dialPicturePath, String needlePicturePath)
	{
		super(dial);
		this.setupPictures(dialPicturePath, needlePicturePath);
		this.needleTransform = new AffineTransform();
		this.sizeCache = this.computeSize();
	}

	private void setupPictures(String dialPicturePath, String needlePicturePath)
	{
		try
		{
			this.dialImage =  ImageIO.read(new File(dialPicturePath));
			this.needleImage = ImageIO.read(new File(needlePicturePath));
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
	private Dimension computeSize()
	{
		if (this.dialImage == null) return super.getSize();
		return new Dimension(this.dialImage.getWidth(), this.dialImage.getHeight());
	}

	public Dimension getSize()
	{
		return this.sizeCache;
	}

		
	@Override
	public void renderBackground(Graphics2D g)
	{
		if (this.dialImage == null) return;
		g.drawImage(this.dialImage,0,0,null);
	}

	@Override
	public void renderNeedle(Graphics2D g)
	{
		if (this.needleImage == null || this.dialImage == null) return;
		
		this.needleTransform.setToIdentity();
		this.needleTransform.translate(this.dialImage.getWidth()/2, this.dialImage.getHeight()/2);
		this.needleTransform.rotate(Math.toRadians(this.dial.getModel().getValue()));
		this.needleTransform.translate(-this.needleImage.getWidth()/2,-this.needleImage.getHeight()/2);

		g.drawImage(this.needleImage,this.needleTransform,null);
	}
}
